package chatUtils

import (
	"fmt"
	"net/http"
	"time"
)

func SendStreamEvent(w http.ResponseWriter, r *http.Request, data string) {

	ctx := r.Context()
	select {
	case <-time.After(10 * time.Millisecond):
		fmt.Fprintf(w, "data: %s\n\n", data)
		if f, ok := w.(http.Flusher); ok {
			f.Flush()
		}
	case <-ctx.Done():
		// 客户端提前断开连接
		//fmt.Println("连接已断开，终止处理")
		return
	}
}

func SendStreamError(w http.ResponseWriter, r *http.Request, msg string) {
	ctx := r.Context()

	select {
	case <-time.After(10 * time.Millisecond):
		// 长时间处理完成
		//fmt.Fprint(w, "处理结果")
		fmt.Fprintf(w, "event: error\ndata: %s\n\n", msg)
		if f, ok := w.(http.Flusher); ok {
			f.Flush()
		}
	case <-ctx.Done():
		// 客户端提前断开连接
		//fmt.Println("连接已断开，终止处理")
		return
	}

}
